import {
  aes_decrypt,
  getSign,
  paramsEncryptAuto,
  rsaEncryptAuto,
} from '@/utils/security.js';
import utils from '@/utils/utils.js';
import MD5 from 'js-md5'; // MD5加密

// #ifdef H5
const Fly = require('flyio/dist/npm/fly');
// #endif

const { NODE_ENV, VUE_APP_PLATFORM, VUE_APP_BASE_URL } = process.env;
const isProxy = NODE_ENV == 'development' && VUE_APP_PLATFORM == 'h5';
const baseURL = isProxy ? '' : `${VUE_APP_BASE_URL}/`;

let aesKey = ''; // 声明全局 aes 密钥
const fly = new Fly();

fly.config.baseURL = baseURL;
fly.interceptors.request.use(
  (request) => {
    aesKey = utils.getAesKey(32); //每次匹配拦截 生成不同的 aes 密钥
    const DeviceType = uni.getSystemInfoSync().deviceType;
    const DeviceId = uni.getSystemInfoSync().deviceId;
    const TimeStamp = new Date().getTime();
    const RandomStrPlaintext = aesKey;
    //console.log(RandomStrPlaintext);
    const RandomStr = rsaEncryptAuto(RandomStrPlaintext);
    let sign = {
      TimeStamp: TimeStamp.toString(),
      UserType: 'buy',
      TerminalType:
        uni.getSystemInfoSync().uniPlatform == 'web' ? 'h5' : 'android',
      DeviceType: DeviceType,
      DeviceId: DeviceId,
      RandomStr: RandomStrPlaintext,
      body: request.body || {},
    };
    //console.log(request);
    request.body =
      request.type == 'encrypt'
        ? paramsEncryptAuto(request.body, aesKey)
        : getSign(request.body);
    //console.log(request.body);
    const newObj = getSign(sign);
    var Sign = JSON.stringify(newObj, (key, val) => {
      if (typeof val === 'undefined') {
        return '';
      }
      return val;
    });
    //console.log(Sign);
    Sign = MD5(Sign).toUpperCase();
    //console.log(Sign);
    request.headers['DeviceType'] = DeviceType;
    request.headers['DeviceId'] = DeviceId;
    request.headers['RandomStr'] = RandomStr;
    request.headers['Sign'] = Sign;
    request.headers['TerminalType'] =
      uni.getSystemInfoSync().uniPlatform == 'web' ? 'h5' : 'android';
    request.headers['TimeStamp'] = TimeStamp.toString();
    request.headers['UserType'] = 'buy';
    return request;
  },
  (error) => Promise.reject(error)
);

fly.interceptors.response.use(
  (response) => {
    const { code, msg } = response.data;
    if (code != 200) {
      uni.showToast({
        title: msg,
        icon: 'none',
      });
    }
    if (response.request.output == 'decrypt') {
      if (response.data.data) {
        response.data.data = JSON.parse(
          aes_decrypt(response.data.data, aesKey)
        );
      }
    }
    return response.data;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

export { fly };
